<template>
    <jb-page>
        <template #conditions>
            <div class="flex-col">
                <div
                    class="flex justify-center items-center pt-8px pb-8px shrink-0 overflow-hidden relative "
                    :class="{dark:darkMode}"
                >
                    <jb-btn
                        size="small"
                        :drawer-component="HiprintTemplate"
                        :drawer-args="{
                            negativeText: '关闭',
                            defaultWidth: '1400',
                            resizable: true
                        }"
                        drawer-positive-text=""
                        drawer-title="模板库"
                        >模版库
                    </jb-btn>
                    <jb-btn
                        class="ml-8px mr-8px"
                        type=""
                        size="small"
                        icon="material-symbols:add"
                        @click="handleNewTemplate"
                        >新模版
                    </jb-btn>

                    <!-- 纸张大小 A3、A4 等 -->
                    <div class="paper flex items-center">
                        <template v-for="(value, type) in state.paperTypes" :key="type">
                            <n-tag
                                :type="curPaperType === type ? 'primary' : ''"
                                class="cursor-pointer"
                                @click="setPaper(type, value)"
                            >
                                {{ type }}
                            </n-tag>
                        </template>

                        <div class="flex items-center ml-8px p1">
                            <n-input
                                v-model:value="customize.width"
                                size="small"
                                style="width: 70px"
                                placeholder="宽(mm)"
                            />
                            <span class="ml-8px mr-8px">x</span>
                            <n-input
                                v-model:value="customize.height"
                                size="small"
                                style="width: 70px"
                                placeholder="高(mm)"
                            />
                        </div>
                        <!-- 自定义纸张 -->
                        <jb-btn
                            :size="'small'"
                            :type="'other' == curPaperType ? 'primary' : ''"
                            icon="mdi:tick"
                            class="auto ml-8px"
                            @click="setCustomize"
                            >自定义
                        </jb-btn>
                    </div>

                    <jb-btn size="small" @click="rotatePaper"> 旋转 </jb-btn>
                    <jb-btn size="small" class="ml-8px" @click="clearPaper">
                        清空
                    </jb-btn>
                    <jb-btn
                        class="ml-8px"
                        icon="mdi:eye"
                        size="small"
                        :modal-component="Preview"
                        :modal-args="{
                            negativeText: '关闭',
                            positiveText: '',
                            defaultWidth: '1400',
                            resizable: true
                        }"
                        modal-title="预览"
                    >
                        预览
                    </jb-btn>
                    <jb-btn
                        icon="mdi:eye"
                        size="small"
                        :drawer-component="TestPreview"
                        :drawer-args="{
                            negativeText: '',
                            defaultWidth: '1400',
                            resizable: true,
                            maskClosable: false
                        }"
                        drawer-positive-text=""
                        drawer-title="Hiprint模板测试数据编辑"
                        class="ml-8px"
                        @drawer-no-click="handleBeforeCloseTest"
                        @drawer-mask-click="handleBeforeCloseTest"
                    >
                        测试预览
                    </jb-btn>
                    <jb-btn
                        ref="saveBtn"
                        class="ml-8px mr-8px"
                        type=""
                        size="small"
                        icon="material-symbols:add"
                        modal-title="保存模板"
                        :modal-component="AddTemplate"
                        :modal-args="{
                            defaultWidth: '600',
                            resizable: true
                        }"
                        @modal-yes-click="handleAdd"
                        >保存模版
                    </jb-btn>
                </div>
                <div
                    class="flex justify-start items-center shrink-0 relative"
                    :class="{dark:darkMode}"
                >
                    <span class="text-14px">分页设计：</span>
                    <div class="hiprint-printPagination"></div>
                </div>
            </div>
        </template>
        <div class="flex h-full" >
            <div class="left w-280px">
                <div class="flex justify-center flex-wrap" >
                    <div
                        class="w-full flex justify-center items-center h-40px flex-wrap"
                        style="border-bottom: 1px solid #ccc"
                    >
                        <div class="flex items-center">
                            <jb-icon
                                class="text-18px"
                                icon="iconamoon:menu-burger-horizontal-fill"
                            />
                            <span class="text-16px ml-2px">可选元素</span>
                        </div>
                    </div>
                    <div class="title">常规</div>
                    <div class="ep-draggable-item item" tid="defaultModule.text">
                        <jb-btn class="jb_btn" icon="icon-park-outline:text"  style="cursor: move;display: flex" >文本</jb-btn>
                    </div>


                    <div class="ep-draggable-item item" tid="defaultModule.longText">
                        <jb-btn icon="zondicons:news-paper"  style="cursor: move" >长文</jb-btn>
                    </div>
                    <div class="ep-draggable-item item" tid="defaultModule.image">
                        <jb-btn icon="ion:image-outline"  style="cursor: move" >图文</jb-btn>
                    </div>
                    <div class="ep-draggable-item item" tid="defaultModule.html">
                        <jb-btn icon="bi:filetype-html"  style="cursor: move" >html</jb-btn>
                    </div>
                    <div class="ep-draggable-item item" tid="defaultModule.barcode">
                        <jb-btn icon="material-symbols:barcode"  style="cursor: move" >条形码</jb-btn>
                    </div>
                    <div class="ep-draggable-item item" tid="defaultModule.qrcode">
                        <jb-btn icon="ic:baseline-qrcode"  style="cursor: move" >二维码</jb-btn>
                    </div>

                    <div class="ep-draggable-item item" tid="defaultModule.table">
                        <jb-btn icon="material-symbols:table"  style="cursor: move" >表格</jb-btn>
                    </div>

                    <div
                        class="ep-draggable-item item"
                        tid="defaultModule.customText"
                        style="visibility: hidden"
                    >
                        <i class="iconfont sv-text" />
                        <span>自定义</span>
                    </div>
                    <div class="title">辅助</div>
                    <div class="ep-draggable-item item" tid="defaultModule.hline">
                        <jb-btn icon="pepicons-pop:line-x"  style="cursor: move" >横线</jb-btn>
                    </div>
                    <div class="ep-draggable-item item" tid="defaultModule.vline">
                        <jb-btn icon="pepicons-pop:line-y"  style="cursor: move" >竖线</jb-btn>
                    </div>
                    <div class="ep-draggable-item item" tid="defaultModule.rect">
                        <jb-btn icon="tdesign:rectangle"  style="cursor: move" >矩阵</jb-btn>
                    </div>
                    <div class="ep-draggable-item item" tid="defaultModule.oval">
                        <jb-btn icon="tabler:circle"  style="cursor: move" >椭圆</jb-btn>
                    </div>
                </div>
            </div>
            <div class="flex-1 center" style="background-color: #fff">
                <!-- 设计器的 容器 -->
                <div id="hiprint-printTemplate" ></div>
            </div>
            <div class="right w-20%">
                <!-- 元素参数的 容器 -->
                <div id="PrintElementOptionSetting"></div>
            </div>
        </div>
    </jb-page>
</template>

<script setup>
import 'jquery'
import { computed, onMounted, reactive, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { defaultElementTypeProvider, hiprint } from 'vue-plugin-hiprint'
import { usePrintStore } from '@/store/modules/print'
import HiprintTemplate from './components/hiprint-template/index.vue'
import AddTemplate from './components/add-template/index.vue'
import Preview from './components/preview/index.vue'
import TestPreview from './components/test-preview/index.vue'
import {useThemeStore} from "@/store";

const { darkMode } = storeToRefs(useThemeStore())
const { hiprintTemplate, info, isNewTemplate } = storeToRefs(usePrintStore())

/**
 * 构建左侧可拖拽元素
 * 注意: 可拖拽元素必须在 hiprint.init() 之后调用
 * 而且 必须包含 class="ep-draggable-item" 否则无法拖拽进设计器
 */

const buildLeftElement = () => {
    // eslint-disable-next-line no-undef
    hiprint.PrintElementTypeManager.buildByHtml($('.ep-draggable-item'))
    hiprint.updateElementType('defaultModule.image', (data) => {
        data.data = import.meta.env.VITE_APP_LOGO_URL
        return data
    })
    hiprint.updateElementType('defaultModule.table', (data) => {
        data.columns = [['', '']]
        data.groupFooterFormatter = undefined
        return data
    })
}

// ref 创建的模板json
// const templateRef = ref(template);
const templateMap = reactive(new Map())

function buildTemplate() {
    $('#hiprint-printTemplate').empty()
    let templates = templateMap.get('KEY_TEMPLATES_PANELS', {
        title: 'jbolt极速开发平台'
    })
    hiprintTemplate.value = new hiprint.PrintTemplate({
        template: templates,
        settingContainer: '#PrintElementOptionSetting',
        paginationContainer: '.hiprint-printPagination',
        defaultPanelName: '默认面板名称',
        onPanelAddClick: (panel, createPanel) => {
            panel.name = '新面板' + (panel.index + 1)
            createPanel(panel)
        },
        onImageChooseClick: (target) => {
            // 创建input，模拟点击，然后 target.refresh 更新
            let input = document.createElement('input')
            input.setAttribute('type', 'file')
            input.click()
            input.onchange = function () {
                let file = this.files[0]
                let reader = new FileReader()
                if (file) {
                    //通过文件流行文件转换成Base64字行串
                    reader.readAsDataURL(file)
                    //转换成功后
                    reader.onloadend = function () {
                        // 通过 target.refresh 更新图片元素
                        target.refresh(reader.result)
                    }
                }
            }
            input.remove()
        }
    })
    hiprintTemplate.value.design('#hiprint-printTemplate', { grid: true })
}

function handleAdd({ close, componentRef }) {
    componentRef.submit().then((res) => {
        close()
        if (isNewTemplate.value) {
            hiprintTemplate.value?.clear()
            isNewTemplate.value = false
        }
    })
}

const saveBtn = ref()

function handleNewTemplate() {
    window.$dialog.warning({
        title: '提示',
        content: '是否保存当前正在编辑的模板?？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
            isNewTemplate.value = true
            saveBtn.value?.showModal()
        },
        onNegativeClick: () => {
            // 关闭弹窗
            close()
            hiprintTemplate.value?.clear()
        }
    })
}

// 数据
const state = reactive({
    curPaper: {
        type: 'A4',
        width: 210,
        height: 296.6
    },
    paperTypes: {
        A3: {
            width: 420,
            height: 296.6
        },
        A4: {
            width: 210,
            height: 296.6
        },
        A5: {
            width: 210,
            height: 147.6
        },
        B3: {
            width: 500,
            height: 352.6
        },
        B4: {
            width: 250,
            height: 352.6
        },
        B5: {
            width: 250,
            height: 175.6
        }
    },
    // 自定义纸张
    paperPopVisible: false,
    paperWidth: '220',
    paperHeight: '80'
})
// 计算属性
const curPaperType = computed(() => {
    let type = 'other'
    let types = state.paperTypes
    for (const key in types) {
        let item = types[key]
        let { width, height } = state.curPaper
        if (item.width === width && item.height === height) {
            type = key
        }
    }
    return type
})

// 方法
const customize = reactive({
    width: '',
    height: ''
})
const setCustomize = () => {
    if (customize.width && customize.height) {
        setPaper('other', customize)
    }
}
const setPaper = (type, value) => {
    try {
        if (Object.keys(state.paperTypes).includes(type)) {
            state.curPaper = { type: type, width: value.width, height: value.height }
            hiprintTemplate.value.setPaper(value.width, value.height)
        } else {
            state.curPaper = { type: 'other', width: value.width, height: value.height }
            hiprintTemplate.value.setPaper(value.width, value.height)
        }
    } catch (error) {
        alert(`操作失败: ${error}`)
    }
}
/**
 * 旋转纸张
 */
const rotatePaper = () => {
    hiprintTemplate.value.rotatePaper()
}
/**
 * 清空所有元素
 */
const clearPaper = () => {
    hiprintTemplate.value.clear()
}

/**
 * 这里必须要在 onMounted 中去构建 左侧可拖拽元素 或者 设计器
 * 因为都是把元素挂载到对应容器中, 必须要先找到该容器
 */
onMounted(() => {
    usePrintStore().$reset()
    buildLeftElement()
    buildTemplate()
})

/**
 * 直接打印: 借助客户端,静默打印(无弹窗直接打印)
 * 注意: 需要先连接客户端
 */
// const print2 = () => {
//     if (hiprint.hiwebSocket.opened) {
//         hiprintTemplate.value.print2({});
//     } else {
//         alert("请先连接客户端(刷新网页), 然后再点击「直接打印」");
//     }
// };

const borderColor = computed(()=>{
    return darkMode.value ? '#fff' :'#000'
})

const codeBgColor = computed(()=>{
    return darkMode.value ? '#fff' :'#ccc'
})

const settingColor = computed(()=>{
    return darkMode.value ? '#18181c' : '#fff'
})

function handleBeforeCloseTest({ close }) {
    window.$dialog.warning({
        title: '提示',
        content: '确认直接关闭编辑器？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
            close()
        }
    })
    throw Error()
}
</script>

<style scoped lang="scss">
/* 重写全局 hiprint 样式 */
.hiprint-headerLine,
.hiprint-footerLine {
    border-color: purple !important;
}

.hiprint-headerLine:hover,
.hiprint-footerLine:hover {
    border-top: 3px dashed purple !important;
}

.hiprint-headerLine:hover:before {
    content: '页眉线';
    left: calc(50% - 18px);
    position: relative;
    background: #ffff;
    top: -14px;
    color: purple;
    font-size: 12px;
}

.hiprint-footerLine:hover:before {
    content: '页脚线';
    left: calc(50% - 18px);
    position: relative;
    color: purple;
    background: #ffff;
    top: -14px;
    font-size: 12px;
}

/* 区域 */
.left {
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    padding: 0;
    box-shadow: 2px 2px 2px 0px #d9d9d9;
    overflow: auto;
}

.center {
    margin: 0 10px;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    padding: 20px;
    box-shadow: 2px 2px 2px 0px #d9d9d9;
    overflow: auto;
}

.right {

    border-radius: 4px;
    border: 1px solid #d9d9d9;
    padding: 10px 0;
    box-shadow: 2px 2px 2px 0px #d9d9d9;
    overflow: auto;
}

/* 左侧拖拽元素样式 */
.title {
    font-size: 16px;
    font-weight: 500;
    width: 100%;
    margin: 10px 0 0 24px;
}

.item {
    display: flex;
    align-items: center;
    margin: 10px 8px 4px 8px;
    width: 38%;
    min-height: 40px;
}



.item .iconfont {
    font-size: 1.5rem;
}

.item span {
    font-size: 14px;
}

/* 纸张 */
.paper {
    margin-right: 10px;
}


</style>
<style>
.hiprint-printPagination {
    display: flex;
    align-items: center;
}
#PrintElementOptionSetting .prop-tabs{
    background-color: v-bind(settingColor)!important;
}
#PrintElementOptionSetting .prop-tab-item{
    background-color: v-bind(settingColor)!important;
}
#PrintElementOptionSetting .hiprint-option-items{
    background-color: v-bind(settingColor)!important;
}



.hiprint-printElement-qrcode,.hiprint-printElement-barcode{
    background-color: v-bind(codeBgColor)!important;
}

.hiprint-printElement-tableTarget-border-td-all{
    background-color: #fff;
}



</style>
